<template>
	<div class="tree">
		<div class="search">
			<ComSearch :isIcon="false" isInput @handleInput="searchKey = $event"></ComSearch>
		</div>
		<a-tree :data="treeData" empty-text="暂无数据" :field-names="fieldNames" :expandAll="true" :blockNode="true" @select="handleNode" ref="treeRef">
			<template #title="nodeData">
				<div style="display:flex; justify-content: space-between; width: 100%;">
					<div class="flex">
						<a-popover position="bottom" class="dept-popover">
							<img src="@/assets/icon-ico.ico" alt="" v-if="nodeData.parentId === 0" class="first">
							<ComAvatar v-else :url="nodeData?.managerUser?.avatar" :name="nodeData?.managerUser?.nickname"/>
							<template #content>
								<div class="user">
									<div class="user-header"> <p> 部门主管</p></div>
									<div class="user-item"><p> 部门名称:</p> {{ nodeData?.label }}</div>
									<div class="user-item"><p> 主管名字:</p> {{nodeData?.managerUser?.nickname  }} </div>
									<div class="user-item"><p> 主管岗位:</p>
										<div>{{nodeData?.managerUser?.postNames.join(',')  }}</div> 
									</div>
								</div>
							</template>
						</a-popover>
						{{nodeData.name}}
					</div>
					<!-- <a-popconfirm position="right">
						<i class="EachApp EachApp_a-bianji1"></i>
						<a-button class="button" :style="{position: 'absolute',top:'180px',left:'350px'}">RB111111</a-button>
						<template #content>
							<a-button @click="handleBtn('add',nodeData)">添加子部门</a-button>
							<a-button @click="handleBtn('edit',nodeData)" class="btn">编辑</a-button>
							<a-button @click="handleBtn('del',nodeData)" class="btn" v-if="nodeData.parentId !== 0">删除</a-button>
						</template>
					</a-popconfirm> -->
					<a-dropdown trigger="click" class="tree-dropdown">
						<i class="EachApp EachApp_a-bianji1"></i>
						<template #content>
							<a-doption>
								<a-button @click="handleBtn('add',nodeData)">添加子部门</a-button>
							</a-doption>
							<a-doption>
								<a-button @click="handleBtn('edit',nodeData)" class="btn">编辑</a-button>
							</a-doption>
							<a-doption>
								<a-button @click="handleBtn('del',nodeData)" class="btn" v-if="nodeData.parentId !== 0">删除</a-button>
							</a-doption>
						</template>
					</a-dropdown>
					<!-- <ComPopover btnType="text" trigger="click" iconfont="EachApp_a-bianji1">
						<template #content>
							<a-button @click="handleBtn('add',nodeData)">添加子部门</a-button>
							<a-button @click="handleBtn('edit',nodeData)" class="btn">编辑</a-button>
							<a-button @click="handleBtn('del',nodeData)" class="btn" v-if="nodeData.parentId !== 0">删除</a-button>
						</template>
					</ComPopover> -->
				</div>
				
			</template>
		</a-tree>
	</div>
	<!-- <div class="tree-btns">
		<a-button  @click="handleBtn('add', {})"><i class="EachApp EachApp_a-tianjia"></i>新建{{ isDept ? '部门' : '岗位' }}</a-button>
	</div> -->
	<ComModal v-model:modalVisible="dialogVisible" :title="title" submitText="保存" @handleSubmit="myComponentRef?.handleSubmit" scroll-to-first-error width="500px">
		<component :is="myComponent" ref="myComponentRef" :currentNode="currentNode" @refreshList="getList(true)" :treeList="treeData"></component>
	</ComModal>
	<ComModal v-model:modalVisible="deleteDeptVisible" title="删除部门" @handleSubmit="handleBtn('delSubmit')" @handleCancel="delSubDept = false" submitText="保存" scroll-to-first-error width="500px">
		<div class="delete-dept-modal">
			<div>确定删除此部门?</div>
			<div class="flex">
				<a-checkbox v-model="delSubDept"></a-checkbox> 删除子部门
			</div>
		</div>
	</ComModal>
</template>
<script lang="ts" setup>
import * as Api from '@/api/common';
import mixins from '@/mixins/index.js';
const { handleMixinSubmit } = mixins();
const message = useMessage();
const Add = defineAsyncComponent(() => import('./Add.vue'));
import mitt from '@/utils/bus';
const searchKey = ref(''); // 关键词
const dialogVisible = ref(false);
const deleteDeptVisible = ref(false);
const deleteDeptInfo = ref({});
const myComponent = ref(null);
const myComponentRef = ref(null);
const currentNode = ref({}); // 当前节点信息
const deptList = ref([]); // 部门列表
const title=ref('添加部门');
const postList = ref([]); // 岗位列表
const tabIndex = ref('dept');
const tabList = ref([
	{ value: 'dept', label: '部门' },
	{ value: 'post', label: '岗位' },
])
watch(() => dialogVisible.value, e => {
	if(!e){
		myComponentRef.value.formRef.resetFields();
	}
})
const delSubDept = ref(false);
const fieldNames = ref ({
    children: 'children',
    title: 'name',
    key:'id',
    isLeaf: 'leaf',
})
const treeRef=ref();
// 是否是部门
const isDept = computed(() => {
	return tabIndex.value === 'dept';
})
// 点击tab
const changeTabs=(e, val)=>{
	tabIndex.value = e;
	nextTick(()=>{
		treeRef.value.selectNode(val?.id ? val?.deptId : treeList.value[0].id ,true);
		if(val?.id){
			handleNode('', { node: val })
		}
	})
}
// 根据部门设置tree的数据
const treeList = computed(() => {
	let arr = deptList.value;
	// if(tabIndex.value === 'post'){
	// 	arr = postList.value;
	// }
	return arr;
})

onMounted(() => {
	getList();
})

// 树列表
const getList = async (isRefresh) => {
	dialogVisible.value = false;
	try{
		const [dept, post] = await Promise.all([
			Api.ApiDeptList(),
			// Api.ApiPostList(),
		]);
		deptList.value = dept;
		postList.value = post;
		nextTick(()=>{
			if(isRefresh){
				
			}else {
				treeRef.value.selectNode(deptList.value[0].id,true);
			}
		})
		nextTick(()=>{
			treeRef.value.expandAll(true);
		})
	}catch(err){console.log(err);}
}

// 点击树节点
const handleNode = (selectedKeys,data) => {
	mitt.emit('handleNode', {
		...data.node,
		postList:postList.value,
		deptList:deptList.value,
		isDept:isDept.value
	});
	currentNode.value = data.node;
}

// 点击tab
const handleTab = (row) => {
	postList.value = [];
	tabIndex.value = tabList.value[+row.index].value;
	getList();
}

// 按钮处理
const handleBtn = async (type, node) => {
	currentNode.value = {
		...(node?.id ? node : currentNode.value),
		isDept:isDept.value,
		btnType: type
	};
	if(['add', 'edit'].includes(type)){
		myComponent.value = Add;
		if(isDept.value){
			title.value = type == 'add' ? '添加部门' : node.name;
		}else {
			title.value = type == 'add' ? '添加岗位' : node.name;
		}
		dialogVisible.value = true;
	}else if(type === 'del'){
		deleteDeptVisible.value = true;
		deleteDeptInfo.value = {...node};
	}else if(type === 'delSubmit'){
		if(isDept.value){
			await handleMixinSubmit(Api.ApiDeptDelete, { id: deleteDeptInfo.value.id, delSubDept: delSubDept.value }, '', false);
		}else {
			await handleMixinSubmit(Api.ApiPostDelete, { id: deleteDeptInfo.value.id }, '', false);
		}
		getList();
		deleteDeptVisible.value = false;
	}
}
mitt.on('getTree', () => {
	getList(true);
})

const treeData = computed(() => {
	if (!searchKey.value) return treeList.value;
	return searchData(searchKey.value);
})

 function searchData(keyword) {
	const loop = (data) => {
		const result = [];
		data.forEach(item => {
		if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
			result.push({...item});
		} else if (item.children) {
			const filterData = loop(item.children);
			if (filterData.length) {
			result.push({
				...item,
				children: filterData
			})
			}
		}
		})
		return result;
	}
	return loop(treeList.value);
}

defineExpose({
	changeTabs
})
</script>

<style lang="scss" scoped>
.tree{
	padding: 10px 10px 10px 0;
	position: relative;
	// height: calc(100% - 50px);
	.search{
		margin-bottom: 10px;
	}
	.first{
		width: 24px;
		height: 24px;
		border-radius: 50%;
	}
	.first,
	.arco-avatar{
		margin-right: 5px;
	}
	.tree-add {
		display: flex;
		justify-content: center;
		margin-bottom: 6px;	
	}
	:deep(.arco-tabs){
		.arco-tabs-content {
			padding-top:0 ;
		}

		.arco-tabs-nav-tab{
			justify-content: center;
		}
	}

	.btn {
		margin-left: 0 !important;
	}
	:deep(.arco-tree){
		height: calc(100% - 42px);
		overflow: auto;
		.arco-tree-node{
			flex-wrap:nowrap;
			&:hover {
				background:#f1f2f3;
			}
		}
		.arco-tree-node-title-text {
			width: 100% !important;
			display: block;
			
		}
		.arco-tree-node-switcher{
			margin-right: 5px !important;
		}
		.EachApp { 
			color: transparent;
		}
		.arco-tree-node-title:hover {
			.EachApp {
				color: #666;
			}
		}
		.arco-tree-node-selected {
			background-color: #f1f2f3;
		}
	}
}
.tree-btns{
	position: absolute;
	bottom: 0;
	left: -8px;
	padding: 10px 0;
	text-align: center;
	width: 220px;
	background: white;
	:deep(.arco-btn){
		margin-left: 5px;
		width: calc(100% - 20px);
	}
}
</style>
<style lang="scss">
	.dept-popover{
		.user{
			font-size: 14px;
			&>div{
				&:not(:last-child){
					margin-bottom: 3px;
				}
			}
			&-header {
				font-weight: 600;
			}
			&-item {
				display: flex;
				p {
					margin-right: 10px;
					color: #999999;
				}
			}
		}
	}
	.delete-dept-modal{
		text-align: center;
		font-size: 16px;
		font-weight: bold;
		.flex{
			font-size: 14px;
			font-weight: normal;
			justify-content: center;
			.arco-checkbox{
				margin-right: 5px;
			}
		}
	}
	.tree-dropdown{
		.arco-dropdown{
			padding: 10px 5px;
		}
		.arco-dropdown-option-content,
		.arco-btn{
			width: 100%;
			margin: 1px 0;
		}
	}
</style>
